package com.polaris.live.popup.party

import android.content.Context
import android.text.SpannableString
import android.text.Spanned
import android.text.style.ForegroundColorSpan
import androidx.core.content.ContextCompat
import com.blankj.utilcode.util.StringUtils
import com.bumptech.glide.Glide
import com.lxj.xpopup.XPopup
import com.lxj.xpopup.core.CenterPopupView
import com.polaris.live.R
import com.polaris.live.common.cacha.UserManager
import com.polaris.live.common.constant.CommonConst
import com.polaris.live.common.ext.autoDp
import com.polaris.live.common.ext.setOnSingleClickListener
import com.polaris.live.common.mvvm.viewmodel.BaseViewModel
import com.polaris.live.common.network.AppException
import com.polaris.live.common.network.requestLoading
import com.polaris.live.common.util.ToastGravity
import com.polaris.live.databinding.PopupJoinRoomJoinMemberBinding
import com.polaris.live.net.liveService
import com.polaris.live.popup.GlobalPopupManager
import com.polaris.live.resp.back_resp.PartyRoomInfoResp
import com.polaris.live.resp.go_resp.JoinMemberRequest
import com.polaris.live.translation.R.string
import com.polaris.live.utils.image.ImageUtils
import com.polaris.live.utils.image.transformRounded

/**
 *  JoinRoomJoinMemberPopup 加入房间提示 加入成员提示
 * @author Created by 天晴 on 2024/3/8 19:18
 * @since 1.0.0
 **/
class JoinRoomJoinMemberPopup(
    context: Context,
    private val mViewModel: BaseViewModel,
    private val mPartyRoomInfoResp: PartyRoomInfoResp,
    private val onCancel: () -> Unit,
    private val onOk: () -> Unit,
) : CenterPopupView(context) {
    private lateinit var mBinding: PopupJoinRoomJoinMemberBinding
    override fun getImplLayoutId(): Int {
        return R.layout.popup_join_room_join_member
    }

    override fun onCreate() {
        super.onCreate()
        mBinding = PopupJoinRoomJoinMemberBinding.bind(popupImplView)
        mBinding.cancel.setOnSingleClickListener {
            dismiss()
        }
        mBinding.cancel.setOnSingleClickListener {
            dismiss()
            onCancel.invoke()
        }
        mBinding.confirm.setOnSingleClickListener {
            if ((UserManager.getUser().account?.coins ?: 0) >= mPartyRoomInfoResp.memberPrice) {
                joinMembers(mViewModel, mPartyRoomInfoResp.roomId, {
                    dismiss()
                    onOk.invoke()
                }) {
                    if (it.errCode == CommonConst.ErrorCode.SENDGIFT) {
                        GlobalPopupManager.showRechargePopup(context, mViewModel, isNeedBottom = true)
                    } else {
                        ToastGravity.showGravity(it.errorMsg)
                    }
                }
            } else {
                GlobalPopupManager.showRechargePopup(context, mViewModel, isNeedBottom = true)
            }

        }

        mBinding.apply {
            val user = mPartyRoomInfoResp.user
            tvRoomName.text = mPartyRoomInfoResp.roomName
            tvMemberCount.text =
                "${StringUtils.getString(string.member)}:(${mPartyRoomInfoResp.member}/${mPartyRoomInfoResp.maxMember})"
            idView.text = StringUtils.getString(string.id, mPartyRoomInfoResp.roomNumber)
            languageView.setLanguage(user.secondLanguage)
            country.setCountry(user.country)
            ageSex.setSexAndAge(user.sex, user.birthday)
            vipView.setVipLevel(user.vipLevel)
            level1.setRichsLevel(user.richs)
            level2.setCharmsLevel(user.charms)
            llFlag.setLabel(user.label)
            Glide.with(context)
                .load(ImageUtils.imgPath(mPartyRoomInfoResp.cover))
                .transformRounded(6.autoDp)
                .into(roomImg)

            tvDiamodCount.text =
                if (mPartyRoomInfoResp.memberPrice <= 0) "(${StringUtils.getString(string.free)})" else "(${mPartyRoomInfoResp.memberPrice}Diamonds)"
        }
    }

    private fun getColoredString(memberPrice: String, baseString: String): SpannableString {
        val fullString = String.format(baseString, memberPrice)
        val spannableString = SpannableString(fullString)
        val startIndex = fullString.indexOf(memberPrice)
        val endIndex = startIndex + memberPrice.length
        val color = ContextCompat.getColor(context, R.color.color_ffa100)
        spannableString.setSpan(ForegroundColorSpan(color), startIndex, endIndex, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE)
        return spannableString
    }


    companion object {

        fun show(
            context: Context,
            mViewModel: BaseViewModel,
            mPartyRoomInfoResp: PartyRoomInfoResp,
            onCancel: () -> Unit,
            onOk: () -> Unit,
        ) {
            XPopup.Builder(context)
                .isViewMode(false)
                .hasShadowBg(true)
                .dismissOnBackPressed(false)
                .dismissOnTouchOutside(false)
                .moveUpToKeyboard(false)
                .isDestroyOnDismiss(true)
                .asCustom(JoinRoomJoinMemberPopup(context, mViewModel, mPartyRoomInfoResp, onCancel, onOk))
                .show()
        }

        /**
         * 加入成员
         */
        fun joinMembers(mViewModel: BaseViewModel, mRoomId: String, ok: () -> Unit, err: (exc: AppException) -> Unit) {
            mViewModel.requestLoading(
                { liveService.joinMembers(JoinMemberRequest(mRoomId)) }, {
                    ToastGravity.showGravity(StringUtils.getString(string.join_success))
                    ok.invoke()
                },
                {
                    err.invoke(it)
                }
            )
        }
    }
}